from pybricks.tools import wait, StopWatch


def waitTouch(
    touch, duration=3000, step=100, msgConfirmed="Touched", msgCanceled="Touch canceled"
):
    """
    Wait for touch sensor to be pressed within a duration.
    :param touch: TouchSensor instance
    :param duration: Maximum time to wait in milliseconds
    :param step: Time interval to check the touch sensor in milliseconds
    :param msgConfirmed: Message to print when touch is confirmed
    :param msgCanceled: Message to print when touch is canceled
    :return: True if touch is confirmed, False if canceled
    """
    confirmed = False
    waitor = StopWatch()
    while waitor.time() < duration:
        confirmed = touch.pressed()
        if confirmed:
            print(msgConfirmed)
            break
        wait(step)
    if not confirmed:
        print(msgCanceled)

    return confirmed
